package com.vf.s.mvc.biz.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.vf.core.model.ZtreeNode;
import com.vf.core.render.RenderLayuiBean;
import com.vf.s.common.model.biz.IconClassify;

public class IconClassifyService {

	protected final Log LOG = Log.getLog(getClass());

	public List<IconClassify> getMenusForUser() {
		return getChildrenAllTree("root");
	}

	public List<IconClassify> getChildrenAllTree(String pId) {
		List<IconClassify> list = getChildrenByPid(pId);
		for (IconClassify o : list) {
			o.setChildren(getChildrenAllTree(o.getId()));
		}
		return list;
	}

	/***
	 * 根据id 查询孩子
	 * 
	 * @param id
	 * @return
	 */
	public List<IconClassify> getChildrenByPid(String id) {
		String sql = "SELECT * FROM "+IconClassify.TABLE_NAME+" M WHERE M.PARENTID='" + id + "'  ";
		sql = sql + " ORDER BY M.SORT";
		return IconClassify.dao.find(sql);
	}

	public RenderLayuiBean listData(Controller menuController) {
		List<IconClassify> list = IconClassify.dao.find(
				"SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "+IconClassify.TABLE_NAME+" WHERE PARENTID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS HAVECHILD   FROM "+IconClassify.TABLE_NAME+"  T  ORDER BY T.SORT ASC");
		RenderLayuiBean renderBean = new RenderLayuiBean();
		renderBean.setCode(0);
		renderBean.setMsg("查询成功");
		renderBean.setData(list);
		renderBean.setCount(list.size());
		return renderBean;
	}

	/***
	 * 菜单转成ZTreeNode
	 * @param olist 数据 open 是否展开所有 ifOnlyLeaf 是否只选叶子
	 * @return
	 */
	public List<ZtreeNode> toZTreeNode(List<IconClassify> olist, Boolean open, Boolean ifOnlyLeaf) {
		List<ZtreeNode> list = new ArrayList<ZtreeNode>();
		for (IconClassify o : olist) {
			ZtreeNode node = toZTreeNode(o);
			if (o.getChildren() != null && o.getChildren().size() > 0) {// 如果有孩子
				node.setChildren(toZTreeNode(o.getChildren(), open, ifOnlyLeaf));
				if (ifOnlyLeaf) {// 如果只选叶子
					node.setNocheck(true);
				}
				node.setIsParent(true);
			}
			node.setOpen(open);
			list.add(node);
		}
		return list;
	}

	public ZtreeNode toZTreeNode(IconClassify org) {
		ZtreeNode node = new ZtreeNode();
		node.setId(org.getId());
		node.setName(org.getName());
		node.setParentId(org.getParentId());
		return node;
	}


}
